import Vue from 'vue'
import Vuex from 'vuex'

import {
  loginAPI
} from '../api/login'

Vue.use(Vuex)

export default new Vuex.Store({
  strict: true, // 严格模式：数据修改只能通过mutations
  state: {
    token: window.localStorage.getItem('token'),
    refreshToken: window.localStorage.getItem('refreshToken'),
    userInfo: {
      photo: window.localStorage.getItem('photo')
    }
  },
  mutations: {
    setToken (state, tokenStr) {
      state.token = tokenStr
      window.localStorage.setItem('token', tokenStr)
    },
    setRefreshToken (state, refreshTokenStr) {
      state.refreshToken = refreshTokenStr
      window.localStorage.setItem('refreshToken', refreshTokenStr)
    },
    setUserPhoto (state, val) {
      state.userInfo.photo = val
      window.localStorage.setItem('photo', val)
    }
  },
  actions: {
    async asyncLoginAction (store, formLogin) {
      // 1.发送登录请求
      const res = await loginAPI(formLogin)
      console.log(res)
      const {
        token,
        refresh_token: refreshToken
      } = res.data.data
      // 2.提交到mutation-同步token和 refreshToken
      store.commit('setToken', token)
      store.commit('setRefreshToken', refreshToken)
    }
  },
  modules: {}
})
